﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SelfService.Model.Models;
using WalkingTec.Mvvm.Core;

namespace SelfService.Helpers
{
    public class ModelFilterAttribute : ActionFilterAttribute
    {
        private readonly WTMContext _wtm;

        public ModelFilterAttribute()
        {

        }

        public ModelFilterAttribute(WTMContext wtm)
        {
            _wtm = wtm;
        }

        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                List<string> err = new List<string>();
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        err.Add(error.ErrorMessage);
                    }
                }
                context.Result = new JsonResult(new Result<object>()
                {
                    Code = 1,
                    Message = string.Join('|', err),
                    Data = null
                });
                if (_wtm != null)
                {
                    _wtm.DoLog($"错误的请求参数:{string.Join("|", err)}", ActionLogTypesEnum.Exception, context.Controller.ToString());
                }
            }
            return base.OnActionExecutionAsync(context, next);
        }
    }
}
